package com.ctgu.tengyun.handler.mybatis;

import com.ctgu.tengyun.util.JsonUtil;
import com.ctgu.tengyun.util.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Objects;

public class JsonStringTypeHandler<T> extends BaseTypeHandler<T> {

    private Class<T> type;

    public JsonStringTypeHandler(Class<T> type) {
        Objects.requireNonNull(type, "Type argument cannot be null");
        this.type = type;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, JsonUtil.getJsonFromObject(parameter));
    }

    @Override
    public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String rewardContent = rs.getString(columnName);
        if (StringUtils.isEmpty(rewardContent)) {
            return null;
        }
        return JsonUtil.getObjectFromJson(rewardContent, type);
    }

    @Override
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String rewardContent = rs.getString(columnIndex);
        if (StringUtils.isEmpty(rewardContent)) {
            return null;
        }
        return JsonUtil.getObjectFromJson(rewardContent, type);
    }

    @Override
    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String rewardContent = cs.getString(columnIndex);
        if (StringUtils.isEmpty(rewardContent)) {
            return null;
        }
        return JsonUtil.getObjectFromJson(rewardContent, type);
    }
}
